package com.example.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * RestTemplate配置
 * @author connor.h.liu
 * @date 2019/6/18 9:31
 */
@Configuration
@ConditionalOnClass(value = {RestTemplate.class, OkHttpClient.class})
public class RestTemplateConfiguration {

  /**
   * 连接池的最大连接数默认为200
   */
  @Value("${http.remote.maxTotalConnect:200}")
  private int maxTotalConnect;
  /**
   * 单个主机的最大连接数默认200
   */
  @Value("${http.remote.maxConnectPerRoute:200}")
  private int maxConnectPerRoute;
  /**
   * 连接超时默认2s
   */
  @Value("${http.remote.connectTimeout:2000}")
  private int connectTimeout;
  /**
   * 读取超时默认10s
   */
  @Value("${http.remote.readTimeout:10000}")
  private int readTimeout;

  /**
   * 创建HTTP客户端工厂
   * @return HTTP客户端工厂
   */
  private ClientHttpRequestFactory createFactory() {
      OkHttp3ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory();
      factory.setConnectTimeout(this.connectTimeout);
      factory.setReadTimeout(this.readTimeout);
      return factory;
  }

  /**
   * 初始化RestTemplate
   * @return RestTemplate
   */
  @Bean
  @ConditionalOnMissingBean(RestTemplate.class)
  public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate(this.createFactory());
    List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();

    //重新设置StringHttpMessageConverter字符集为UTF-8，解决中文乱码问题
    HttpMessageConverter<?> converterTarget = null;
    for (HttpMessageConverter<?> item : converterList) {
      if (StringHttpMessageConverter.class == item.getClass()) {
        converterTarget = item;
        break;
      }
    }
    if (null != converterTarget) {
      converterList.remove(converterTarget);
    }
    converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

    //加入FastJson转换器
    converterList.add(new FastJsonHttpMessageConverter4());
    return restTemplate;
  }

}
